// 这个文件似乎是为了解耦而解耦 正确与否 未知
import { ref, nextTick } from 'vue'

import AiTalkRequest from '@/api/aiTalkRequest'

// 采用单例模式 保证ai对话内容的唯一性
class OperatorAITalk {
  constructor() {
    this.aiTalkingList = ref([])
  }
  // 更新客户端对话信息
  clinetCtx(content, uuid) {
    this.aiTalkingList.value.push({
      type: 'client',
      value: content,
      sign: uuid
    })
  }
  // 更新服务端对话信息
  async serviceCtx(response) {
    const serviceMessageIndex = this.aiTalkingList.value.length
    this.aiTalkingList.value.push({
      type: 'service',
      answer: ''
    })
    // 读取流数据
    const reader = response.body.getReader()
    // 实例化容器
    const decoder = new TextDecoder()
    let result = ''
    try {
      while (true) {
        // 解构所需变量
        const { done, value } = await reader.read()
        // 结束跳出循环
        if (done) {
          break
        }
        // 解码数据
        const chunk = decoder.decode(value, { stream: true })
        result += chunk

        this.aiTalkingList.value[serviceMessageIndex].value = result

        await nextTick()
      }
    } catch (error) {
      console.error('读取流数据时出错:', error)
    } finally {
      reader.releaseLock()
    }
  }
  // 向服务端发送请求
  async serviceCtxRequest(content) {
    const aiTalkRequest = new AiTalkRequest('http://127.0.0.1:3333', {})
    await aiTalkRequest.post('/dpTalk', {
      content: content
    })
  }
}

const aiTalkListInstance = (() => {
  let instance
  return () => {
    if (!instance) {
      instance = new OperatorAITalk()
    }
    return instance
  }
})()

export default aiTalkListInstance
